
import json
import logging
import requests
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from .models import Notification
from django.conf import settings

logger = logging.getLogger(__name__)


def send_sms(phone, content):
    """
    发送短信
    
    Args:
        phone: 手机号
        content: 短信内容
    """
    try:
        # TODO: 集成实际的短信服务商API
        # 这里只是记录日志，实际项目中需要调用短信服务商的API
        logger.info(f"向 {phone} 发送短信: {content}")
        
        # 示例：调用短信服务商API
        # url = "https://api.sms-service.com/send"
        # data = {
        #     "apikey": settings.SMS_API_KEY,
        #     "phone": phone,
        #     "content": content,
        #     "sign": settings.SMS_SIGN
        # }
        # response = requests.post(url, json=data)
        # if response.status_code != 200:
        #     logger.error(f"短信发送失败: {response.text}")
        #     return False
        # return True
        
        return True
    except Exception as e:
        logger.error(f"短信发送异常: {str(e)}")
        return False


def send_notification(notification):
    """
    发送通知消息到WebSocket
    
    Args:
        notification: Notification对象
    """
    try:
        # 获取通道层
        channel_layer = get_channel_layer()
        
        # 构建消息数据
        message = {
            'type': 'notification',
            'data': {
                'notification_id': notification.id,
                'title': notification.title,
                'content': notification.content,
                'notification_type': notification.notification_type,
                'notification_type_display': notification.get_notification_type_display(),
                'level': notification.level,
                'level_display': notification.get_level_display(),
                'is_read': notification.is_read,
                'created_at': notification.created_at.isoformat(),
                'related_order_id': notification.related_order.id if notification.related_order else None
            }
        }
        
        # 发送消息到组
        group_name = f'user_{notification.recipient.id}_notifications'
        async_to_sync(channel_layer.group_send)(
            group_name,
            message
        )
        
        logger.info(f"Notification sent to {group_name}")
    except Exception as e:
        logger.error(f"Error sending notification: {str(e)}")


def send_bulk_notifications(notifications):
    """
    批量发送通知消息到WebSocket
    
    Args:
        notifications: Notification对象列表
    """
    for notification in notifications:
        send_notification(notification)